//
//  FLHomeViewController.swift
//  swift_learning
//
//  Created by aron on 2017/1/16.
//  Copyright © 2017年 arons. All rights reserved.
//

import UIKit
import SVProgressHUD
import MJRefresh

class HomeViewController: UITableViewController {

    fileprivate lazy var titleButton: FLTitleButton = FLTitleButton()
    fileprivate lazy var statusViewModels = [StatusViewModel]()
    
    lazy var newStatusCountTipLabel : UILabel = UILabel()
    
    /// 自定义的弹出视图代理
    private lazy var animator : FLPresentationAnimator = {
       let animator = FLPresentationAnimator()
        animator.presentCallback = {[weak self](presented : Bool) -> () in
            self?.titleButton.isSelected = presented
        }
        return animator
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化View
        setupContentView()

        // 导航栏初始化
        setupNavigationBar()
        
        // 设置提示Label
        setupStatusCountLabel()
        
        // 请求首页数据 --> 在下拉刷新中处理
        // loadStatus()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let name = UserAccountManager.sharedInstance.account?.screen_name ?? ""
        titleButton.setTitle(name, for: .normal)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - ......::::::: init :::::::......
    
    private func setupContentView() {
        // 注册Cell
        tableView.register(UINib(nibName: "StatusCell", bundle: nil), forCellReuseIdentifier: "StatusCell")
        
        // 自动计算高度
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        
        // 分割线
        tableView.separatorStyle = .none
        
        // 下拉刷新
        let refreshHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeViewController.onPullRefresh))
        tableView.mj_header = refreshHeader
        refreshHeader?.beginRefreshing()
        
        // 上拉加载更多
        let refreshFooter = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(HomeViewController.onPullUpLoadMore))
        tableView.mj_footer = refreshFooter
        
    }
    
    private func setupStatusCountLabel() {
        newStatusCountTipLabel.frame = CGRect(x: 0, y: 20, width: SCREEN_WIDTH(), height: 32)
        navigationController?.navigationBar.insertSubview(newStatusCountTipLabel, at: 0)
        navigationController?.navigationBar.sendSubview(toBack: newStatusCountTipLabel)
        
        newStatusCountTipLabel.backgroundColor = UIColor.orange
        newStatusCountTipLabel.textColor = UIColor.white
        newStatusCountTipLabel.font = UIFont.systemFont(ofSize: 12)
        newStatusCountTipLabel.textAlignment = .center
        newStatusCountTipLabel.isHidden = false
    }
    
    
    /// 导航栏初始化
    private func setupNavigationBar() {
        if (UserAccountManager.sharedInstance.isLogin()) == false {
            navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(HomeViewController.onRegClick))
            navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(HomeViewController.onLoginClick))
        }else {
            let name = UserAccountManager.sharedInstance.account?.screen_name ?? ""
            titleButton.setTitle(name, for: .normal)
            titleButton.addTarget(self, action: #selector(HomeViewController.onTitleBtnClick), for: .touchUpInside)
            navigationItem.titleView = titleButton
            
            navigationItem.leftBarButtonItem = UIBarButtonItem(title: "测试", style: .plain, target: self, action: #selector(HomeViewController.onTest))
        }
    }
    
    // MARK: - ......::::::: ui action :::::::......
    
    @objc private func onRegClick() {
        BMLOG("")
    }
    
    @objc private func onLoginClick() {
        BMLOG("")
        let authVC = FLOAuthViewController()
        let authNVC = UINavigationController(rootViewController: authVC)
        present(authNVC, animated: true, completion: nil)
    }
    
    @objc private func onTest() {
        navigationController?.pushViewController(TestViewController(), animated: true)
    }
    
    @objc private func onTitleBtnClick() {
        BMLOG("")

        // 弹出菜单
        let popViewWidth : CGFloat = 160;
        let popViewHeight : CGFloat = 200;
        animator.presentedFrame = CGRect(x: (SCREEN_WIDTH()-popViewWidth)/2, y: 60, width: popViewWidth, height: popViewHeight)
        let popoverVC = PopoverViewController()
        popoverVC.modalPresentationStyle = .custom
        popoverVC.transitioningDelegate = animator
        present(popoverVC, animated: true, completion: nil)
    }
    
    
    /// 下拉刷新
    @objc private func onPullRefresh() {
        loadStatus(isLoadMore: false)
    }
    
    /// 上拉加载更多
    @objc private func onPullUpLoadMore() {
        loadStatus(isLoadMore: true)
    }
}


// MARK: - TableViewDelegate
extension HomeViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return statusViewModels.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "StatusCell") as! StatusCell
        cell.setStatus(statusViewModels[indexPath.row])
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}


// MARK: - 网络请求
extension HomeViewController {
    
    /// 获取微博列表
    fileprivate func loadStatus(isLoadMore : Bool) {
        
        // 刷新
        SVProgressHUD.show()
        
        // 处理参数
        var since_id = 0
        var max_id = 0
        if isLoadMore {
            max_id = statusViewModels.last?.status?.mid ?? 0
            max_id = max_id == 0 ? 0 : (max_id - 1)
        } else {
            since_id = statusViewModels.first?.status?.mid ?? 0
        }
        
        NetworkTools.sharedInstance.requestStatus(since_id: since_id, max_id: max_id){[weak self] (statuses : [Status]?, error : Error?) in
            
            if let statusArr = statuses {
                var tmpStatusVMs = [StatusViewModel]()
                for status in statusArr {
                    let statusVM = StatusViewModel(status: status)
                    tmpStatusVMs.append(statusVM)
                }
                
                if isLoadMore {
                    // 加载更多
                     self?.statusViewModels.append(contentsOf: tmpStatusVMs)
                } else {
                    // 下拉刷新
                    self?.statusViewModels.insert(contentsOf: tmpStatusVMs, at: 0)
                }
            }
            
            // 停止刷新
            SVProgressHUD.dismiss()
            
            // 停止下拉刷新
            if isLoadMore {
                self?.tableView.mj_footer.endRefreshing()
            } else {
                self?.tableView.mj_header.endRefreshing()
                
                // 显示更新微博提示
                self?.showNewStatusCount(count: statuses?.count ?? 0)
                // self?.showNewStatusCount(count: 12)
            }
            
            // 刷新数据
            self?.tableView.reloadData()
        }
    }

    
    /// 显示更新微博提示
    ///
    /// - Parameter count: 更新微博数
    private func showNewStatusCount(count : Int) {
        if count > 0 {
            // 设置提示信息
            newStatusCountTipLabel.isHidden = false
            newStatusCountTipLabel.text = "更新了\(count)条微博"
            
            // 执行动画
            UIView.animate(withDuration: 1.0, animations: {[weak self] in
                self?.newStatusCountTipLabel.frame.origin.y = 44
            }) {[weak self] (_) in
                UIView.animate(withDuration: 1.0, delay: 1.5, options: [], animations: {
                    self?.newStatusCountTipLabel.frame.origin.y = 0
                }, completion: { (_) in
                    self?.newStatusCountTipLabel.isHidden = true
                })
            }
        }
    }
}


